<template>
  <div id="mini-container" ref="containerRef" class="cesium-container"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import cesiumUtils from "@/utils/cesiumUtils";
import eventBus from "@/utils/other/eventBus";
import tilesConfig from '@/config/tiles.json'

const emit = defineEmits(["map-loaded"]);

let cesiumTools = null;
let viewer = null;
const containerRef = ref(null);
let cameraChangeEvent = null;

// 添加3DTiles
function add3DTiles() {
  tilesConfig.tiles.forEach(tile => {
    const tileSet = cesiumTools.add3DTile(tile.url, tile.options)
    viewer.zoomTo(tileSet)
  })
}

onMounted(() => {
  try {
    const container = document.getElementById("mini-container");
    cesiumTools = cesiumUtils(container);
    viewer = cesiumTools.init({
      homeButton: false,
      geocoder: false,
      sceneModePicker: false,
      openDebug: false,
      startGlobeRotate: false,
      defaultImagery: 0,
      navigation: false
    });

    add3DTiles();

    // 监听主地图无人机空间状态，联动相机
    eventBus.on(
      "uav-camera-sync",
      ({ position, heading, pitch, distance, fov }) => {
        if (!viewer || !position) return;
        viewer.camera.lookAt(
          position,
          new Cesium.HeadingPitchRange(
            Cesium.Math.toRadians(heading - 90), // 朝向
            Cesium.Math.toRadians(-pitch + 90), // 俯仰
            distance // 距离目标点的距离（米）
          )
        );
        viewer.camera.frustum.fov = Cesium.Math.toRadians(fov);

        if (!cameraChangeEvent) {
          // 监听用户手动拖拽/缩放事件（忽略代码触发的相机变化）
          cameraChangeEvent = viewer.camera.changed.addEventListener(syncView);
          // 设置相机变化的灵敏度阈值，只有当相机参数变化超过0.01时才会触发changed事件
          viewer.camera.percentageChanged = 0.01;
        }
      }
    );

    

    // 监听鼠标滚轮事件，调整相机fov，实现缩放效果
    viewer.scene.canvas.addEventListener(
      "wheel",
      event => {
        event.preventDefault();
        // 获取当前fov，单位为弧度
        let fov = viewer.camera.frustum.fov;
        // 设置缩放步长，越小越灵敏
        const step = Cesium.Math.toRadians(5);

        if (event.deltaY < 0) {
          // 向上滚动，缩小fov（放大视角）
          fov -= step;
        } else {
          // 向下滚动，增大fov（缩小视角）
          fov += step;
        }
        // 限制fov范围，避免过大或过小
        fov = Cesium.Math.clamp(
          fov,
          Cesium.Math.toRadians(5),
          Cesium.Math.toRadians(30)
        );
        viewer.camera.frustum.fov = fov;
        // 主动同步到主地图
        syncView();
      },
      { passive: false }
    );

    // 同步主地图视椎体变化
    const syncView = () => {
      if (!viewer || !viewer.camera) return;
      const { heading, pitch } = viewer.camera;
      eventBus.emit("miniMap-camera-change", {
        heading: Cesium.Math.toDegrees(heading) + 90,
        pitch: Cesium.Math.toDegrees(-pitch) + 90,
        fov: Cesium.Math.toDegrees(viewer.camera.frustum.fov)
      });
    };

    // 启用旋转（改变相机视角）
    viewer.scene.screenSpaceCameraController.enableRotate = true;
    // 禁用其他所有操作
    viewer.scene.screenSpaceCameraController.enableZoom = false; // 禁用缩放
    viewer.scene.screenSpaceCameraController.enableTilt = false; // 禁用倾斜
    viewer.scene.screenSpaceCameraController.enableTranslate = false; // 禁用平移
    viewer.scene.screenSpaceCameraController.enableLook = false; // 禁用自由观看
    viewer.scene.screenSpaceCameraController.inertiaSpin = 0; // 禁用惯性旋转
    viewer.scene.screenSpaceCameraController.inertiaZoom = 0; // 禁用惯性缩放

    // 发出地图加载完成事件
    emit("map-loaded", cesiumTools, viewer);
  } catch (error) {
    console.error("Error initializing Cesium:", error);
  }
});

onBeforeUnmount(() => {
  if (cesiumTools) {
    cesiumTools.destroy();
  }
  if (cameraChangeEvent) {
    // 移除事件
    viewer.camera.changed.removeEventListener(cameraChangeEvent);
    cameraChangeEvent = null;
  }
});
</script>

<style scoped lang="scss">
.cesium-container {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
}
</style>
